<?php

namespace app\admin\controller\yunfood\food;

use addons\yunfood\model\FoodLike as GoodsLikeModel;
use app\admin\model\yunfood\Food;
use app\admin\model\yunfood\SysUser;
use addons\yunfood\library\Backend;

/**
 * 菜品收藏
 */
class Like extends Backend
{
    /**
     * @var GoodsLikeModel
     */
    protected $model;

    // 联表查询，解决字段冲突
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsLikeModel();

        // 状态
        $this->view->assign('statusList', $this->model::getStatusList());
        $this->assignconfig('statusList', $this->model::getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 转发到selectGoodsLike
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);
            $this->request->get(['filter' => $filter, 'op' => $op]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->with(['food_data', 'user_data'])
                ->field('food_like.*')
                ->join([Food::getTableName() => 'food'], 'food.id=food_like.food_id',
                    'LEFT')
                ->join([SysUser::getTableName() => 'user'], 'user.id=food_like.user_id', 'LEFT')
                ->where($where)->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }

        // 商品列表
        $foodList = Food::getOptionList();
        $this->view->assign('foodList', $foodList);
        $this->assignconfig('foodList', $foodList);

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);

        return [json_encode($filter), json_encode($op)];
    }

    public function add()
    {
        return;
    }

    public function edit($ids = null)
    {
        return;
    }
}
